package com.leetcode.June;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 合并区间
 * @Author: Mr.Fxy
 * @CreateTime: 2024-07-09 16:23
 */
public class mergeSect {
    public static int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
        List<int[]> res = new ArrayList<>();
        for (int[] p : intervals) {
            int m= res.size();
            if (m>0 && p[0]<=res.get(m-1)[1]) {
                res.get(m - 1)[1] = Math.max(res.get(m - 1)[1], p[1]);
            }else { // 不相交，无法合并
                res.add(p); // 新的合并区间
            }
        }
        return res.toArray(new int[res.size()][]);
    }

    public static void main(String[] args) {
        int[][] cs={{1,3},{2,6},{8,10},{15,18}};
        int[][] merge = merge(cs);
        for (int i = 0; i < merge.length; i++) {
            for (int j = 0; j < merge[i].length; j++) {
                System.out.print(merge[i][j] + " ");
            }
            System.out.println();
        }
    }
}
